package com.iemp.security.handler;

import com.iemp.config.consts.ApiConsts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CustomAccessDeniedHandlerImpl extends AccessDeniedHandlerImpl {
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        Cookie[] cookies = request.getCookies();
        String jwt = "";
        for (Cookie cookie : cookies) {
            jwt = "access_token".equals(cookie.getName()) ? cookie.getValue() : jwt;
        }
        String eMessage = "权限不足，无法执行操作:" + jwt;
        log.error(eMessage);
        response.sendRedirect(ApiConsts.LOGIN_PAGE);
        super.handle(request, response, accessDeniedException);
    }
}
